<template>
  <div>
    <kline-chart :data="klineArray" @change="onChange">
      <span>{{ activeData.symbol }}/{{ activeData.title }}</span>
      <span :style="{color: getColor('number',latestData.change)}">{{ latestData.change_rate.toFixed(2) }}%</span>
    </kline-chart>
    <van-nav-bar right-text="筛选" @click-right="showPopup2=true">
      <template #title>
        <van-tabs v-model="activeName1" type="card" :color="activeName1 === 'long_buy' ? '#ee0a24' : '#07c160'" @click="onFlagChange"
                  @change="onFlagChange">
          <van-tab title="开多" name="long_buy"/>
          <van-tab title="开空" name="short_sell"/>
        </van-tabs>
      </template>
      <template #left>
        <timer-load v-if="!loading" url="/china_future/stamps/obtain" period="d" @confirm="onConfirm"/>
      </template>
    </van-nav-bar>
    <custom-table ref="tableRef" :columns="tableColumns" :records="tableData.datas"
                  :style="{ height: `${tableHeight}px` }" @onClick="onCheck" @onSort="onSort"/>
    <pager v-model="queryParams.page" :total="tableData.total" :limit="queryParams.limit"
           :count="tableData.datas.length" @change="load"/>
    <nav-bar path="/signal" @change="path => $router.push(`${path}/future`)"/>
    <van-popup v-model="showPopup1" position="bottom" :style="{ height: '80%' }">
      <strategy-check-box :direction="queryParams.direction" :side="queryParams.side" url="/china_future/policy/obtain"
                          @confirm="onModule"/>
    </van-popup>
    <van-popup v-model="showPopup2" position="bottom" :style="{ height: '80%' }">
      <van-tabs v-model="activeName2">
        <van-tab title="因子" name="a">
          <van-nav-bar title="编辑因子" left-text="重置" right-text="确认" @click-left="() => {
                        tempModule = {
                            d: {},
                            w: {},
                            m: {}
                        }
                    }" @click-right="onQuery"/>
          <factor-form v-model="tempModule.d" period="d" :factorList="factorList"/>
          <factor-form v-model="tempModule.w" period="w" :factorList="factorList"/>
          <factor-form v-model="tempModule.m" period="m" :factorList="factorList"/>
        </van-tab>
        <van-tab title="周期" name="b">
          <van-nav-bar title="选择周期" left-text="重置" right-text="确认" @click-left="queryParams.period = 'd'"
                       @click-right="onQuery"/>
          <van-radio-group v-model="queryParams.period">
            <van-cell-group>
              <van-cell v-for="item in $types.periodTypes" :key="item.value"
                        :title="item.text"
                        clickable @click="queryParams.sequence = item.value">
                <template #right-icon>
                  <van-radio :name="item.value"/>
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </van-tab>
        <van-tab title="主次" name="c">
          <van-nav-bar title="选择主次" left-text="重置" right-text="确认" @click-left="queryParams.sequence = 0"
                       @click-right="onQuery"/>
          <van-radio-group v-model="queryParams.sequence">
            <van-cell-group>
              <van-cell v-for="(n, index) in 25" :key="n"
                        :title="index>0?`次${index.toString().padStart(2, '0')}`:'主力'"
                        clickable @click="queryParams.sequence = index">
                <template #right-icon>
                  <van-radio :name="index"/>
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </van-tab>
      </van-tabs>
    </van-popup>
    <van-popup v-model="showPopup3" position="bottom" :style="{ height: '80%' }">
      <ticker-view :title="activeData.title" :market="activeData.market" :symbol="activeData.symbol"
                   @industry="onIndustry"
                   @create="onCreate"
                   @delete="onDelete"
                   @close="showPopup3 = false"/>
      <van-divider>
        <span v-if="activeData.state">{{ activeData.description }}</span>
      </van-divider>
      <description-list :columns="3" :data="activeList" @sort="item=>onFront(item.field)"/>
    </van-popup>
  </div>
</template>

<script>
import {getKlines, getTicker} from '@/interfaces/eastmoney'
import {deepMerge, getOptionsTarget, numberFormat} from '@/utils'

export default {
  components: {
    ColorText: () => import('@/components/ColorText.vue'),
    CustomTable: () => import('@/components/CustomTable.vue'),
    DescriptionList: () => import('@/components/DescriptionList.vue'),
    FactorForm: () => import('@/components/FactorForm.vue'),
    KlineChart: () => import('@/components/KlineChart.vue'),
    StrategyCheckBox: () => import('@/components/StrategyCheckBox.vue'),
    NavBar: () => import('@/components/NavBar.vue'),
    Pager: () => import('@/components/Pager.vue'),
    TickerView: () => import('@/components/TickerView.vue'),
    TimerLoad: () => import('@/components/TimerLoad.vue'),
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 404
    }
  },
  data() {
    return {
      activeName1: 'long_buy',
      activeName2: 'a',
      activeData: {
        title: '商品期货综合指数',
        symbol: 'emcom',
        market: 'dc',
        industry: '-',
        description: null
      },
      latestData: {
        change: 0,
        change_rate: 0,
        price: 0
      },
      activeList: [],
      factorList: [],
      moduleList: [],
      policyList: [],
      klineArray: [],
      klinePeriod: 'd',
      queryParams: {
        page: 1,
        limit: 20,
        order_by: 'state',
        sort_direction: -1,
        timestamp: null,
        sequence: 0,
        period: 'd',
        direction: 'long',
        side: 'buy'
      },
      showPopup1: false,
      showPopup2: false,
      showPopup3: false,
      tempModule: {
        d: {},
        w: {},
        m: {}
      },
      tableColumns: [],
      frontFields: [],
      tableData: {
        total: 0,
        datas: []
      },
      loading: true
    }
  },
  methods: {
    getOptionsTarget: getOptionsTarget,
    load() {
      let payload = Object.assign(
        {
          config: this.getOptions()
        },
        this.queryParams
      )
      this.$requests.post('/china_future/signal/obtain', payload).then(resp => {
        this.tableData = resp
        if (resp.total > 0) {
          if (this.activeData.market !== resp.datas[0].market || this.activeData.symbol !== resp.datas[0].symbol) {
            this.activeData = Object.assign(this.activeData, resp.datas[0])
          }
        }
        this.onFormat()
        this.setHistory()
        this.setColumns()
      })
    },
    getFactorList() {
      this.$requests.post('/china_future/factor/obtain', {
        page: 1,
        limit: 1000,
        order_by: 'sequence',
        sort_direction: 1,
        enabled: true
      }).then(resp => {
        this.factorList = resp.datas
        this.loading = false
      })
    },
    getColor(category, value) {
      if (category === 'string' || value === 0) {
        return '#2c3e50'
      } else {
        return value > 0 ? '#F56C6C' : '#67C23A'
      }
    },
    getOptions() {
      let tempObject = deepMerge({
        d: {
          sector: {
            eq: 'future',
          }
        }
      }, this.tempModule)
      if (typeof (this.queryParams.sequence) === 'number') {
        tempObject = deepMerge({
          d: {
            sequence: {eq: this.queryParams.sequence},
          }
        }, tempObject)
      }
      for (let i = 0; i < this.moduleList.length; i++) {
        tempObject = deepMerge(this.moduleList[i].config, tempObject)
      }
      return tempObject
    },
    getFactors() {
      let tempObject = {}
      for (let j = 0; j < this.factorList.length; j++) {
        for (let i = 0; i < this.$types.periodTypes.length; i++) {
          if (this.factorList[j].typeof !== 'string') {
            let field = this.$types.periodTypes[i].value + '_' + this.factorList[j].field
            if (Object.hasOwnProperty.call(this.activeData, field)) {
              this.$set(tempObject, field, {
                title: this.$types.periodTypes[i].text + this.factorList[j].title,
                field: field,
                value: this.activeData[field],
                scale: this.factorList[j].typeof === 'integer' ? 0 : 3,
                unity: this.factorList[j].typeof === 'percentage' ? '%' : '',
                blurb: this.factorList[j].description
              })
            }
          }
        }
      }
      return Object.values(tempObject)
    },
    setColumns() {
      let tempObject = {
        title: {
          title: '名称',
          field: 'title',
          renderCell: (row) => {
            return `<div style="color:${row.state ? '#ee0a24' : '#1989fa'};">${row.title}</div>`
          }
        },
        state: {
          title: '审核',
          field: 'state',
          renderCell: (row) => {
            if (row.state) {
              return `<div style="color: #ee0a24;">✔</div>`
            } else {
              return `<div style="color: #2c3e50;">✔</div>`
            }
          }
        },
      }
      for (let j = 0; j < this.factorList.length; j++) {
        for (let i = 0; i < this.$types.periodTypes.length; i++) {
          if (this.factorList[j].typeof !== 'string') {
            let field = this.$types.periodTypes[i].value + '_' + this.factorList[j].field
            if (Object.hasOwnProperty.call(this.activeData, field)) {
              this.$set(tempObject, field, {
                title: this.$types.periodTypes[i].text + this.factorList[j].title,
                field: field,
                renderCell: (row) => {
                  let color = this.getColor(this.factorList[j].typeof, row[field])
                  let value = this.factorList[j].typeof === 'integer' ? numberFormat(row[field], 0) : numberFormat(row[field], 3)
                  let unity = this.factorList[j].typeof === 'percentage' ? '%' : ''
                  return `<div style="color:${color};">${value}${unity}</div>`
                }
              })
            }
          }
        }
      }
      let tableColumns = {}
      tableColumns['title'] = tempObject['title']
      tableColumns['state'] = tempObject['state']
      for (let i = 0; i < this.frontFields.length; i++) {
        let field = this.frontFields[i]
        tableColumns[field] = tempObject[field]
      }
      tableColumns = Object.assign(tableColumns, tempObject)
      this.tableColumns = Object.values(tableColumns)
    },
    setHistory() {
      getKlines({
        market: this.activeData.market,
        symbol: this.activeData.symbol,
        period: this.klinePeriod,
        adjust: 'qfq'
      }, resp => {
        this.klineArray = resp
      })
    },
    onFlagChange(value) {
      let temp = value.split('_')
      this.queryParams.direction = temp[0]
      this.queryParams.side = temp[1]
      this.showPopup1 = true
    },
    onConfirm(value) {
      this.queryParams.timestamp = value
      this.onQuery()
    },
    onCreate(row) {
      let description = this.moduleList.map(item => {
        return item.title
      }).join()
      this.$requests.post('/china_future/signal/create', {
        timestamp: this.queryParams.timestamp,
        title: row.title,
        market: row.market,
        symbol: row.symbol,
        period: this.queryParams.period,
        direction: this.queryParams.direction,
        side: this.queryParams.side,
        price: this.latestData.price,
        description: description,
        contrived: true
      }).then(resp => {
        if (resp) {
          this.activeData = Object.assign(this.activeData, {
            state: 1,
            description: description
          })
          this.load()
        }
      })
    },
    onDelete(row) {
      this.$requests.post('/china_future/signal/delete', {
        timestamp: this.queryParams.timestamp,
        market: row.market,
        symbol: row.symbol,
        period: this.queryParams.period,
        direction: this.queryParams.direction,
        side: this.queryParams.side
      }).then(resp => {
        if (resp.n) {
          this.activeData.state = 0
          this.load()
        }
      })
    },
    onIndustry(name) {
      this.showPopup3 = false
      this.$router.push(`/whole/future?sector=board&title=${name}`)
    },
    onFormat() {
      getTicker(this.activeData.market, this.activeData.symbol, resp => {
        this.latestData = {
          change: resp.close - resp.pre_close,
          change_rate: (resp.close / resp.pre_close - 1) * 100,
          price: resp.close
        }
      })
    },
    onModule(moduleList) {
      this.showPopup1 = false
      this.moduleList = moduleList
      this.onQuery()
    },
    onChange(period) {
      this.klinePeriod = period
      this.setHistory()
    },
    onCheck(row, field) {
      this.activeData = row
      this.onFormat()
      this.setHistory()
      if (field === 'title') {
        this.activeList = this.getFactors()
        this.showPopup3 = true
      } else if (field === 'state') {
        if (row.state) {
          this.onDelete(row)
        } else {
          this.onCreate(row)
        }
      }
    },
    onQuery() {
      this.showPopup1 = false
      this.showPopup2 = false
      this.showPopup3 = false
      this.page = 1
      this.load()
    },
    onFront(filed) {
      let idx = this.frontFields.indexOf(filed)
      if (idx > -1) {
        this.frontFields.splice(idx, 1)
      }
      this.frontFields.unshift(filed)
      this.showPopup3 = false
      this.setColumns()
    },
    onSort(order_by, sort_direction) {
      this.queryParams.order_by = order_by
      this.queryParams.sort_direction = sort_direction
      this.showPopup3 = false
      this.load()
    }
  },
  mounted() {
    this.getFactorList()
  }
}
</script>

<style scoped>
.van-col {
  color: #fff;
  font-size: 14px;
  padding-left: 6px;
  text-align: left;
}
</style>
